package com.example.demo.service;

import com.example.demo.model.Danmaku;
import com.example.demo.model.User;
import com.example.demo.repository.DanmakuRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@RequiredArgsConstructor
public class DanmakuService {

    private final DanmakuRepository danmakuRepository;

    /**
     * 获取所有弹幕
     */
    @Cacheable("allDanmakus")
    public List<Danmaku> getAllDanmakus() {
        return danmakuRepository.findAllOrderByCreatedTimeDesc();
    }

    /**
     * 获取最新的弹幕
     *
     * @param limit 限制返回的数量
     * @return 最新的弹幕列表
     */
    @Cacheable(value = "recentDanmakus", key = "#limit")
    public List<Danmaku> getRecentDanmakus(int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        return danmakuRepository.findByOrderByCreatedTimeDesc(pageable);
    }

    /**
     * 创建弹幕
     */
    @Transactional
    @CacheEvict(value = {"allDanmakus", "recentDanmakus"}, allEntries = true)
    @Async
    public CompletableFuture<Danmaku> createDanmaku(User user, String content, Integer colorType) {
        Danmaku danmaku = new Danmaku();
        danmaku.setUser(user);
        danmaku.setContent(content);
        danmaku.setColorType(colorType);
        danmaku.setCreatedTime(LocalDateTime.now());
        
        return CompletableFuture.completedFuture(danmakuRepository.save(danmaku));
    }

    /**
     * 删除弹幕
     */
    @Transactional
    @CacheEvict(value = {"allDanmakus", "recentDanmakus"}, allEntries = true)
    public void deleteDanmaku(Long id) {
        danmakuRepository.deleteById(id);
    }

    /**
     * 保存新弹幕
     * @param danmaku 弹幕实体
     * @return 保存后的弹幕实体
     */
    @Transactional
    @CacheEvict(value = {"allDanmakus", "recentDanmakus"}, allEntries = true)
    @Async
    public CompletableFuture<Danmaku> saveDanmaku(Danmaku danmaku) {
        if (danmaku.getCreatedTime() == null) {
            danmaku.setCreatedTime(LocalDateTime.now());
        }
        return CompletableFuture.completedFuture(danmakuRepository.save(danmaku));
    }
    
    /**
     * 批量保存弹幕（用于性能优化）
     * @param danmakus 弹幕列表
     * @return 保存后的弹幕列表
     */
    @Transactional
    @CacheEvict(value = {"allDanmakus", "recentDanmakus"}, allEntries = true)
    public List<Danmaku> saveAllDanmakus(List<Danmaku> danmakus) {
        return danmakuRepository.saveAll(danmakus);
    }
} 